package view

import (
	"context"
	"web-ppt/internal/consts"
	"web-ppt/internal/logic/session"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/gogf/gf/v2/util/gmode"
)

type View struct{}

func New() *View {
	return &View{}
}

func (v *View) RenderTpl(ctx context.Context, tpl string, data interface{}) {
	viewData := gconv.Map(data)
	if viewData == nil {
		viewData = make(map[string]interface{})
	}

	userinfo := session.New().Get(ctx, consts.User)
	if userinfo != nil {
		viewData["userinfo"] = "编辑模式"
	} else {
		viewData["userinfo"] = "展示模式"
	}

	for k, v := range viewData {
		if g.IsEmpty(v) {
			delete(viewData, k)
		}
	}
	// 渲染模板
	request := g.RequestFromCtx(ctx)
	_ = request.Response.WriteTpl(tpl, viewData)

	// 开发模式下，在页面最下面打印所有的模板变量
	if mode, _ := g.Cfg().Get(ctx, "server.serverMode"); mode.String() != "test" {
		if gmode.IsDevelop() {
			err := request.Response.WriteTplContent(`{{dump .}}`, viewData)
			if err != nil {
				panic(err)
			}
		}
	}
}

func (v *View) RenderTplContent(ctx context.Context, tpl string, data interface{}) {
	viewData := gconv.Map(data)
	if viewData == nil {
		viewData = make(map[string]interface{})
	}

	for k, v := range viewData {
		if g.IsEmpty(v) {
			delete(viewData, k)
		}
	}
	// 渲染模板
	request := g.RequestFromCtx(ctx)
	_ = request.Response.WriteTplContent(tpl, viewData)

	// 开发模式下，在页面最下面打印所有的模板变量
	if gmode.IsDevelop() {
		err := request.Response.WriteTplContent(`{{dump .}}`, viewData)
		if err != nil {
			panic(err)
		}
	}
}

func (v *View) Page(ctx context.Context, total, size int) string {
	r := g.RequestFromCtx(ctx)
	page := r.GetPage(total, size)
	page.LinkStyle = "page-link"
	page.SpanStyle = "page-link"
	page.PrevPageTag = "«"
	page.NextPageTag = "»"
	content := page.PrevPage() + page.PageBar() + page.NextPage()

	content = gstr.ReplaceByMap(content, map[string]string{
		"<span":  "<li class=\"page-item disabled\"><span",
		"/span>": "/span></li>",
		"<a":     "<li class=\"page-item\"><a",
		"/a>":    "/a></li>",
	})
	return "<ul class=\"pagination justify-content-center\">" + content + "</ul>"
}
